package com.meida.archive.admin.listener;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.starter.redis.core.RedisKeyChangeListener;
import com.meida.starter.redis.core.RedisMessageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 监控文件上传实现挂载功能
 *
 * @author Administrator
 */
@Component
@Slf4j
public class MyRedisListener implements RedisKeyChangeListener {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public String getTopicName() {
        return "minio_upload";
    }

    @Override
    public void onSuccess(String message, String redisKey) {
        log.info("key发生变化===》" + message);
        log.info(redisKey);

        List<Map<String, Object>> fileList = jdbcTemplate.query("SELECT * FROM minio_log WHERE status = 0", new RowMapper<Map<String, Object>>() {
            @Override
            public Map<String, Object> mapRow(ResultSet rs, int i) {
                Map<String, Object> map = new HashMap<>();
                try {
                    Integer id = rs.getInt("id");
                    String fileName = rs.getString("key_name");
                    String value = rs.getString("value");
                    JSONObject result = JSONObject.parseObject(value);
                    if (FlymeUtils.isNotEmpty(result)) {
                        JSONArray records = result.getJSONArray("Records");
                        JSONObject record = records.getJSONObject(0);
                        JSONObject s3 = record.getJSONObject("s3");
                        JSONObject userIdentity = record.getJSONObject("userIdentity");
                        String principalId = userIdentity.getString("principalId");
                        JSONObject object = s3.getJSONObject("object");
                        JSONObject userMetadata = object.getJSONObject("userMetadata");
                        Object userId = userMetadata.get("X-Amz-Meta-Userid");
                        //当userId是空的时候代表是通过工具上传上去的
                        if (FlymeUtils.isEmpty(userId)) {
                            jdbcTemplate.update("update minio_log set userName=? where id=?", new Object[]{principalId, id});
                        }
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return map;
            }
        });
    }
}
